package org.example.service.impl;


import org.example.constant.MessageConstant;
import org.example.domain.GoodsDeposit;
import org.example.domain.Warehouse;
import org.example.dto.GoodsDto;
import org.example.exception.NumberErrorException;
import org.example.mapper.WarehouseMapper;
import org.example.service.GoodsDepositService;
import org.example.mapper.GoodsDepositMapper;
import org.example.vo.GoodsDepositVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

/**
 * @author SweetPig
 * @description 针对表【a_goods_deposit】的数据库操作Service实现
 * @createDate 2024-05-29 15:17:08
 */
@Service
public class GoodsDepositServiceImpl implements GoodsDepositService {

    @Autowired
    private GoodsDepositMapper goodsDepositMapper;

    @Autowired
    private WarehouseMapper warehouseMapper;


    public List<GoodsDepositVo> getById(Integer id) {
        return goodsDepositMapper.getById(id);
    }

    @Override
    public List<GoodsDeposit> list() {
        return goodsDepositMapper.list();
    }


    @Override
    public boolean delGoods(GoodsDto goodsDto) {
        Integer id = goodsDto.getId();
        Warehouse warehouse = warehouseMapper.getById(id);
        Integer capacity = warehouse.getCapacity();
        if (capacity < goodsDto.getNum()){
            throw new NumberErrorException(MessageConstant.NUM_ERROR);
        }
        List<GoodsDepositVo> list = goodsDto.getList();
        //出库数量
        Integer num = goodsDto.getNum();
        for (GoodsDepositVo goodsDepositVo : list) {
            Integer warehousingNum = goodsDepositVo.getWarehousingNum();
            if (warehousingNum <= num){
                num = num -warehousingNum;
                goodsDepositMapper.delGoods(goodsDepositVo.getId());
            }else {
                //修改库存 (warehousingNum - num) 修改容量 （capacity - num）
                goodsDepositVo.setWarehousingNum(warehousingNum-num);
                goodsDepositMapper.updateById(goodsDepositVo);
                goodsDto.setCapacity(capacity-num);
                warehouseMapper.updateById(goodsDto);
                return true;
            }
        }
        return false;
    }
}




